//
//  LHPasswordView.m
//  LHPassword
//
//  Created by YueHui on 16/2/19.
//  Copyright © 2016年 Leihou Software co. All rights reserved.
//

#import "LHYPassword.h"

// 屏幕bounds
#define LHScreenBounds [UIScreen mainScreen].bounds
#define LHScreenW [UIScreen mainScreen].bounds.size.width
#define kWindow [UIApplication sharedApplication].keyWindow

// 字体设置
#define LHYFont(CGFloat) [UIFont systemFontOfSize:CGFloat]

@interface LHYPassword ()

///返回密码
@property (nonatomic , strong) NSString *password;
///响应者
@property (nonatomic , strong) UITextField *responsder;
///密码框组合
@property (nonatomic, strong) UIView *fieldView;
///密码框数组
@property (nonatomic, strong) NSMutableArray *fields;
///密码框隐藏方向
@property (nonatomic , assign) LHYPasswordAnimationDirection directionHiden;
///密码框出现方向
@property (nonatomic , assign) LHYPasswordAnimationDirection directionShow;

@end
@implementation LHYPassword

- (instancetype)init {
    if (self = [super init]) {
        
        self.pwdWidth = 50;
        self.pwdCount = 6;
        self.pwdY = 74;
        /** 默认隐藏方向从左边出去 */
        self.directionHiden = LHYPasswordAnimationDirectionFromLeftOut;
        /** 默认出现方向从右边进入 */
        self.directionShow = LHYPasswordAnimationDirectionFromRightIn;
        /** 动画默认时间3s */
        self.duration = .5f;
        /** 响应者 */
        [self setupResponsder];
        
    }
    return self;
}
/** 响应者 */
- (void)setupResponsder
{
    UITextField *responsder = [[UITextField alloc] init];
    responsder.keyboardType = UIKeyboardTypePhonePad;
    
    [responsder addTarget:self action:@selector(txchange:) forControlEvents:UIControlEventEditingChanged];
    
    self.responsder = responsder;
    [kWindow addSubview:self.responsder];
    
}
- (void)showWithAnimated:(BOOL)animated {
    
    [self.responsder becomeFirstResponder];
    [kWindow addSubview:self.fieldView];
    if (animated) {
        
        switch (self.directionShow) {
            case LHYPasswordAnimationDirectionFromRightIn: {
                break;
            }
            case LHYPasswordAnimationDirectionFromLeftIn: {
                CGPoint center = self.fieldView.center;
                center.x = - self.fieldView.bounds.size.width/2;
                self.fieldView.center = center;
                
                break;
            }
            default:
                break;
        }
        
        [UIView animateWithDuration:self.duration animations:^{
            
            CGPoint center = self.fieldView.center;
            center.x = kWindow.center.x;
            self.fieldView.center = center;
        }];

    }
    else {
        
        CGPoint center = self.fieldView.center;
        center.x = kWindow.center.x;
        self.fieldView.center = center;
    }
    
}
- (void)hideWithAnimated:(BOOL)animated {
    
    if (animated) {
        switch (self.directionHiden) {
            case LHYPasswordAnimationDirectionFromLeftOut: {
                
                [UIView animateWithDuration:self.duration animations:^{
                    
                    CGPoint fieldViewCenter = self.fieldView.center;
                    fieldViewCenter.x = - self.fieldView.bounds.size.width/2;
                    self.fieldView.center = fieldViewCenter;
                    
                } completion:^(BOOL finished) {
                    
                    [self.responsder resignFirstResponder];
                }];
                
                break;
            }
            case LHYPasswordAnimationDirectionFromRightOut: {
                
                [UIView animateWithDuration:self.duration animations:^{
                    
                    CGRect fra = self.fieldView.frame;
                    fra.origin.x = LHScreenW;
                    self.fieldView.frame = fra;
                    
                } completion:^(BOOL finished) {
                    
                    [self.responsder resignFirstResponder];
                }];
                
                break;
            }
            default:
                break;
        }
        
    }
    else {
        [self.responsder resignFirstResponder];
        [self.fieldView removeFromSuperview];
    }
    
}
- (void)showWithAnimated:(BOOL)animated direction:(LHYPasswordAnimationDirection)direction {
    
    self.directionShow = direction;
    [self showWithAnimated:animated];
}

- (void)hideWithAnimated:(BOOL)animated direction:(LHYPasswordAnimationDirection)direction {

    self.directionHiden = direction;
    [self hideWithAnimated:animated];
}
#pragma mark 文本框内容改变
- (void)txchange:(UITextField *)tx
{
    self.password = tx.text;

    for (int i = 0; i < _pwdCount; i++)
    {
        UITextField *pwdtx = [self.fields objectAtIndex:i];
        if (i < self.password.length)
        {
            NSString *pwd = [self.password substringWithRange:NSMakeRange(i, 1)];
            pwdtx.text = pwd;
        }
        else
        {
            pwdtx.text = @"";
        }
        
    }
    
    if (_password.length == _pwdCount)
    {
        tx.text = [tx.text substringToIndex:_pwdCount];

        if (self.isRemoteCheck)
        {
            if ([self.delegate respondsToSelector:@selector(password:remoteCheckingWithString:)]) {
                [self.delegate password:self remoteCheckingWithString:self.password];
            }
        }
        else
        {
            if ([self.delegate respondsToSelector:@selector(password:checkingWithString:)]) {
                BOOL checkResult = [self.delegate password:self checkingWithString:self.password];
                if (checkResult) {
                    [self hideWithAnimated:YES];
                }
                else {
                    [self shakeAnimationForView:self.fieldView];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        self.responsder.text = @"";
                        [self txchange:self.responsder];
                    });
                }
            }
        }
        
    }
    
}

- (void)remoteCheckingWithResult:(BOOL)result
{
    if (!self.isRemoteCheck)
    {
        return;
    }
    if (result)
    {
        [self hideWithAnimated:YES];
    }
    else
    {
        [self shakeAnimationForView:self.fieldView];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.responsder.text = @"";
            [self txchange:self.responsder];
        });
    }
}

#pragma mark - Property
- (UIView *)fieldView {
    if (!_fieldView) {
        _fieldView = [[UIView alloc] initWithFrame:CGRectMake(LHScreenW, _pwdY, _pwdWidth * _pwdCount, _pwdWidth)];
        for (int i = 0; i < _pwdCount ; i++) {
            UITextField *field = self.fields[i];
            [_fieldView addSubview:field];
        }

    }
    return _fieldView;
}
- (NSMutableArray *)fields
{
    if (!_fields) {
        NSMutableArray *arr = [NSMutableArray array];
        for (int i = 0; i < _pwdCount; i++)
        {
            UITextField *pwdLabel = [[UITextField alloc] initWithFrame:CGRectMake(i * (_pwdWidth - 1), 0, _pwdWidth, _pwdWidth)];
            pwdLabel.layer.borderColor = [UIColor lightGrayColor].CGColor;
            pwdLabel.borderStyle = UITextBorderStyleNone;
            pwdLabel.enabled = NO;
            pwdLabel.font = LHYFont(25);
            pwdLabel.textAlignment = NSTextAlignmentCenter;//居中
            pwdLabel.secureTextEntry = YES;//设置密码模式
            pwdLabel.backgroundColor = [UIColor whiteColor];
            pwdLabel.layer.borderWidth = 1;
            
            [arr addObject:pwdLabel];
        }
        _fields = [NSMutableArray arrayWithArray:arr];
        
    }
    return _fields;
}
#pragma mark 抖动动画
- (void)shakeAnimationForView:(UIView *) view {
    // 获取到当前的View
    CALayer *viewLayer = view.layer;
    // 获取当前View的位置
    CGPoint position = viewLayer.position;
    // 移动的两个终点位置
    CGPoint x = CGPointMake(position.x + 5, position.y);
    CGPoint y = CGPointMake(position.x - 5, position.y);
    // 设置动画
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    // 设置运动形式
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
    // 设置开始位置
    [animation setFromValue:[NSValue valueWithCGPoint:x]];
    // 设置结束位置
    [animation setToValue:[NSValue valueWithCGPoint:y]];
    // 设置自动反转
    [animation setAutoreverses:YES];
    // 设置时间
    [animation setDuration:.06];
    // 设置次数
    [animation setRepeatCount:3];
    // 添加上动画
    [viewLayer addAnimation:animation forKey:nil];
}

@end
